package com.hellogood.yaohuo.server.mgr;

import java.util.List;

import org.apache.log4j.Logger;

import com.hellogood.yaohuo.server.dao.factory.DAOFactory;
import com.hellogood.yaohuo.shared.entity.Detail;
import com.hellogood.yaohuo.shared.entity.Form;
import com.hellogood.yaohuo.shared.entity.ThForm;
import com.hellogood.yaohuo.shared.exception.DatabaseException;

public class FanchangMgr {
	private Logger log = Logger.getLogger(this.getClass());
	private String tableFormName = "ThForm";
	private String tableDetailName = "ThDetail";
	private String billNoField = "ThBillNo";
	private String dateField = "ThDate";

	public List<Form> searchFanchangFormByOrgCodeAndDate(String code, int level, String startDate, String endDate, String rz) {
		if (code.equals("0")) {
			return DAOFactory.getInstance().createThFormDAO().searchFormByQuyu(tableFormName, billNoField, dateField, null, startDate, endDate, rz);
		} else {
			return DAOFactory.getInstance().createThFormDAO().searchForm(tableFormName, billNoField, dateField, code, startDate, endDate, rz);			
		}
		/*
		 * if (level == 2) { return
		 * DAOFactory.getInstance().createThFormDAO().searchThFormByQuyu(code,
		 * startDate, endDate, rz); } else if (level == 3) { return
		 * DAOFactory.getInstance().createThFormDAO().searchThForm(code,
		 * startDate, endDate, rz); } else if (level == 1) { return
		 * DAOFactory.getInstance().createThFormDAO().searchThFormByQuyu(null,
		 * startDate, endDate, rz); } return null;
		 */
	}

	public Form getFormDetail(String billNo) {
		Form form = DAOFactory.getInstance().createThFormDAO().getFormByBillNo(tableFormName, billNoField, dateField, billNo);		
		if (form != null) {
			List<Detail> list = DAOFactory.getInstance().createThDetailDAO().getDetailByBillNo(billNo, tableDetailName, billNoField);
			form.setList(list);
		}
		return form;
	}

	public String deleteForm(String billNo) {
		return DAOFactory.getInstance().createThFormDAO().deleteForm(tableFormName, tableDetailName, billNoField, billNo);
	}

	public String saveForm(ThForm form, boolean isModify) {
		return DAOFactory.getInstance().createThFormDAO().createTuihuo(form, isModify);
	}

	public String rz(List<String> bills) {
		String result = "";
		try {
			for (String bill : bills) {
				String temp = DAOFactory.getInstance().createThFormDAO().rz(bill);
				if (!temp.equals("")) {
					result = temp;
					break;
				}
			}
		} catch (DatabaseException e) {
			log.error(e.getMessage());
			e.printStackTrace();
			result = e.getMessage();
		}
		return result;
	}

	public int getLastFcBillNo(String billNo) {
		String no = DAOFactory.getInstance().createThFormDAO().getLastBillNo(billNo, "ThForm", "ThBillNo");
		if (no != null) {
			// 序号为最后两位 格式为"WLYH组织号YYYYMMDDXX" XX为序号
			if (no.length() > 4) {
				String lastNo = no.substring(no.length() - 4, no.length());
				return Integer.valueOf(lastNo);
			}
		}
		return 0;
	}
}